<template>
  <div>
    <div v-if="!(chatList.length > 0) && condition === true">
      <div class="welcome-header">
        <img class="welcome-image" :src="Union" alt="" />
        <span>我是AI物料助手，很高兴见到你！</span>
      </div>
      <div class="welcome-subtext">
        我可以回答你物料的一些问题，请把向我提问吧~
      </div>
    </div>
    <div
      v-if="!(chatList.length > 0) && condition === false"
      class="welcome-simple"
    >
      我可以回答你物料的一些问题，请把向我提问吧~
    </div>
    <t-chat
      layout="single"
      :style="
        chatList.length > 0
          ? { height: '78vh', width: '100%' }
          : { height: '66vh', width: '100%' }
      "
      :data="chatList"
      :clear-history="chatList.length > 0 && !isStreamLoad"
      :text-loading="loading"
      :is-stream-load="isStreamLoad"
      @on-action="operation"
      @clear="clearConfirm"
    >
      <!-- eslint-disable-next-line vue/no-unused-vars -->

      <template #content="{ item }">
        <div class="markdown-container" v-if="item.content">
          <MarkdownContent :content="item.content" />
        </div>

        <div v-if="item.hasTable && item.tableData" class="table-container">
          <DynamicTable :data="item.tableData" />
        </div>
        <div v-if="item.pullTableData"><pullTable></pullTable></div>
      </template>
      <template #actions="{ item, index }">
        <t-chat-action
          :content="item.content"
          :operation-btn="['replay', 'copy']"
          @operation="(type) => handleOperation(type, item, index)"
        />
      </template>
      <!-- <template #footer>
                <t-chat-input v-model="localChatValue" :stop-disabled="isStreamLoad" @send="inputEnter" @stop="onStop">
                </t-chat-input>
            </template> -->
      <template #footer>
        <t-chat-sender
          v-model="localChatValue"
          :textarea-props="{
            placeholder: '请输入你需要的内容',
          }"
          :loading="loading"
          :stop-disabled="isStreamLoad"
          @send="inputEnter"
          @stop="onStop"
        >
          <template #suffix="{ renderPresets }">
            <component
              v-if="isStreamLoad"
              style="display: none"
              :is="renderPresets([])"
            />
            <xcmg-button
              v-if="!isStreamLoad"
              type="primary"
              theme="default"
              variant="text"
              @click="handleSendClick"
            >
              <img
                style="margin-bottom: 4px"
                src="@/assets/images/star.png"
                alt=""
              />
              <div class="button-spacer"></div>
              发送
            </xcmg-button>
          </template>
        </t-chat-sender>
      </template>
    </t-chat>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { streamPost, getTableData } from "@/util/http";
import Union from "@/assets/images/Union.png";
import avatar from "@/assets/images/avatar.jpg";
import MarkdownContent from "@/components/MarkdownContent.vue";
import DynamicTable from "@/components/DynamicTable.vue";
import pullTable from "@/components/pullTable/index.vue";
import marked from "@/components/marked.vue";

const props = defineProps({
  chatValue: Object,
  condition: {
    type: Boolean,
    default: false,
  },
});
const localChatValue = ref(props.chatValue || "");

watch(
  () => props.chatValue,
  (newVal) => {
    localChatValue.value = `我想问${newVal.label}` || "";
  }
);

const loading = ref(false);
const isStreamLoad = ref(false);
const currentAssistantIndex = ref(-1);
const eventSourceRef = ref<EventSource | null>(null);
const abortControllerRef = ref<AbortController | null>(null);

const formatTime = (date: Date) => {
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const inputDate = new Date(date);

  const timeStr = inputDate.toTimeString().substring(0, 5);

  if (inputDate >= today) {
    return `今天 ${timeStr}`;
  } else if (inputDate >= new Date(today.setDate(today.getDate() - 1))) {
    return `昨天 ${timeStr}`;
  } else {
    return `${inputDate.getMonth() + 1}/${inputDate.getDate()}`;
  }
};

const chatList = ref([
  {
    avatar: Union,
    name: "物料规范AI",
    datetime: "昨天16:38",

    //         content: `**已确认参数：**
    // - 物料名称：柴油发动机

    // **问题参数：**
    // - 排量：您输入的"排量200"未匹配到允许填写的参数列表中的"排量 (L)"。标准的排量范围为1.0–16.0 L。您提供的值超出了这一范围，可能是单位错误。请确认您希望提供的排量值，例如"排量 (L): 16.0"。

    // **缺失参数：**
    // 1. **排量 (L)**：排量是指发动机所有气缸工作容积的总和，是衡量发动机大小的重要指标。对于柴油发动机，典型的排量范围为1.0–16.0 L。请提供具体的排量值。
    // 2. **缸径 × 行程 (mm)**：缸径和行程分别指气缸的直径和活塞的行程长度，这两个参数直接影响发动机的性能和效率。建议值范围为80–160 mm × 90–200 mm。请提供具体的缸径和行程值。
    //         `,
    hasTable: true,
    // tableData: [
    //   {
    //     "中文名称(规范库)": "物料名称",
    //     "英文名称(GDM)": "Material Name(Industry Standard Description)",
    //     "业务定义及用途(规范库)":
    //       "用于在系统中标识和区分不同的物料，按照标准化名称进行填写。",
    //     "业务规则(规范库)":
    //       "Q/XCMG 1L811.1—2024 物料主数据 第1部分：总则 (试行)",
    //     "数据类型(GDM)": "文本",
    //     "数据长度(GDM)": "50",
    //     "是否有允许值(GDM)": "否",
    //   },
    //   {
    //     "中文名称(规范库)": "设计类物料类别",
    //     "英文名称(GDM)": "Design Material Categories",
    //     "业务定义及用途(规范库)":
    //       "自定义属性，初始用于设计三表所需分类，其后完善为所有物料的初始分类，可作为后续业务属性参照的基础。",
    //     "业务规则(规范库)":
    //       "对于EBOM中的物料，设计初始定义，如不能明确采购/自制，优先填写Z自制，工艺MPM阶段进行确认修改。",
    //     "数据类型(GDM)": "文本",
    //     "数据长度(GDM)": "30",
    //     "是否有允许值(GDM)": "是",
    //   },
    // ],
    pullTableData: true,
    role: "assistant",
  },
  {
    avatar: avatar,
    name: "自己",
    datetime: "昨天16:38",
    content: "你好",
    role: "user",
  },
]);

// 重新生成
const handleOperation = function (type: string, item: any, index: number) {
  console.log("handleOperation", type, item, index);
  if (type === "replay") {
    regenerateResponse(index);
  }
};

const operation = function (type: string, options: any) {
  console.log(type, options);
};

const clearConfirm = function () {
  chatList.value = [];
};

const onStop = function () {
  if (abortControllerRef.value) {
    abortControllerRef.value.abort();
    abortControllerRef.value = null;
  }
  isStreamLoad.value = false;
  loading.value = false;
};

// 重新生成响应函数
const regenerateResponse = function (index: number) {
  if (isStreamLoad.value) return;

  const userMessageIndex = index + 1;
  if (
    userMessageIndex >= chatList.value.length ||
    chatList.value[userMessageIndex].role !== "user"
  ) {
    console.error("No user message found for regeneration");
    return;
  }

  const userMessage = chatList.value[userMessageIndex].content;
  const currentTime = new Date();

  // 重置助手消息（清空内容 + 清除表格）
  chatList.value[index] = {
    ...chatList.value[index],
    content: "",
    hasTable: false,
    tableData: [],
    datetime: formatTime(currentTime),
  };

  currentAssistantIndex.value = index;
  startStreamRequest(userMessage);
};

const startStreamRequest = async function (inputValue: string) {
  if (isStreamLoad.value) return;

  // 中断之前的请求
  if (abortControllerRef.value) {
    abortControllerRef.value.abort();
  }

  const controller = new AbortController();
  abortControllerRef.value = controller;

  isStreamLoad.value = true;
  loading.value = true;

  const assistantIndex = currentAssistantIndex.value;
  const sessionId = "abc123";

  try {
    // === 第一步：使用封装的 streamPost 方法进行流式请求 ===
    await streamPost(
      "/stream",
      {
        query: inputValue,
        session_id: sessionId,
      },
      controller,
      (chunk) => {
        // 处理数据流
        if (chunk && assistantIndex !== -1 && chatList.value[assistantIndex]) {
          chatList.value[assistantIndex].content += chunk;
        }
        loading.value = false;
      },
      () => {
        // 流结束后开始请求表格数据
        if (controller.signal.aborted) return;

        getTableData(sessionId)
          .then((tableData) => {
            console.log("tableData", tableData);
            if (
              Array.isArray(tableData) &&
              tableData.length > 0 &&
              assistantIndex !== -1 &&
              chatList.value[assistantIndex]
            ) {
              chatList.value[assistantIndex].hasTable = true;
              chatList.value[assistantIndex].tableData = tableData;
            }
          })
          .catch((error) => {
            if (!controller.signal.aborted) {
              console.error("获取表格数据失败:", error);
              if (assistantIndex !== -1 && chatList.value[assistantIndex]) {
                chatList.value[
                  assistantIndex
                ].content += `\n\n[获取表格数据时出错：${error.message}]`;
              }
            }
          });
      },
      (error) => {
        // 错误处理
        if (!controller.signal.aborted) {
          console.error("流式请求失败:", error);
          if (assistantIndex !== -1 && chatList.value[assistantIndex]) {
            chatList.value[
              assistantIndex
            ].content += `\n\n[获取数据时出错：${error.message}]`;
          }
        }
      }
    );
  } catch (error: any) {
    if (controller.signal.aborted) {
      console.log("Request was aborted");
    } else {
      console.error("请求失败:", error);
      if (assistantIndex !== -1 && chatList.value[assistantIndex]) {
        chatList.value[
          assistantIndex
        ].content += `\n\n[获取数据时出错：${error.message}]`;
      }
    }
  } finally {
    // 清理
    if (abortControllerRef.value === controller) {
      abortControllerRef.value = null;
    }
    isStreamLoad.value = false;
    loading.value = false;
    currentAssistantIndex.value = -1;
  }
};

const handleSendClick = function () {
  if (localChatValue.value.trim()) {
    inputEnter(localChatValue.value);
  }
};

const inputEnter = function (inputValue: string) {
  if (isStreamLoad.value || !inputValue?.trim()) return;

  const currentTime = new Date();
  chatList.value.unshift({
    avatar: "https://tdesign.gtimg.com/site/avatar.jpg",
    name: "自己",
    datetime: formatTime(currentTime),
    content: inputValue,
    role: "user",
  });

  chatList.value.unshift({
    avatar: Union,
    name: "物料规范AI",
    datetime: formatTime(currentTime),
    content: "",
    hasTable: false,
    tableData: [],
    role: "assistant",
  });

  currentAssistantIndex.value = 0;
  startStreamRequest(inputValue);
  localChatValue.value = "";
};

const handleStreamError = function (errorMsg: string) {
  if (currentAssistantIndex.value !== -1) {
    chatList.value[currentAssistantIndex.value].content = errorMsg;
    chatList.value[currentAssistantIndex.value].role = "error";
  }
  if (eventSourceRef.value) {
    eventSourceRef.value.close();
    eventSourceRef.value = null;
  }
  isStreamLoad.value = false;
  loading.value = false;
  currentAssistantIndex.value = -1;
};
</script>

<style scoped lang="less">
/* 替换 Tailwind CSS 的样式 */
.welcome-header {
  display: flex;
  font-size: 26px;
  justify-content: center;
}

.welcome-image {
  padding-top: 0;
  padding-right: 0.5rem;
  width: 2.75rem;
}

.welcome-subtext {
  padding-top: 1rem;
  text-align: center;
}

.welcome-simple {
  padding-top: 0.5rem;
  font-size: 16px;
  text-align: center;
}

.markdown-container {
  margin-left: 1rem;
  font-size: 16px;
}

.table-container {
  margin: 16px;
}

:deep(.t-chat__detail) {
  width: calc(100% - 32px);
}

:deep(.t-chat__avatar) {
  padding-top: 0;
}

:deep(.t-chat__actions .t-button) {
  color: #555d6d;
}

:deep(.el-button) {
  padding: 8px 10px !important;
}

::-webkit-scrollbar-thumb {
  background-color: var(--td-scrollbar-color);
}

::-webkit-scrollbar-thumb:horizontal:hover {
  background-color: var(--td-scrollbar-hover-color);
}

::-webkit-scrollbar-track {
  background-color: var(--td-scroll-track-color);
}
</style>
